<?php
/*
Plugin Name: Donation
Plugin URI: http://www.kieranoshea.com/projects/donation
Description: Allows blog visitors to offer a donation to the author
Author: Kieran O'Shea
Author URI: http://www.kieranoshea.com
Version: 1.0
*/

/*  Copyright 2011  Kieran O'Shea  (email : kieran@kieranoshea.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

// Enable internationalisation
$plugin_dir = basename(dirname(__FILE__));
load_plugin_textdomain( 'donation','wp-content/plugins/'.$plugin_dir, $plugin_dir);

// Setup variable for table
global $wpdb;
define('WP_DONATION_TABLE', $wpdb->prefix . 'donation');

// Add filter to the_content
add_filter('the_content', 'showDonation');
add_filter('the_excerpt', 'showDonation');
add_filter('the_content_rss', 'showDonation');
add_filter('the_excerpt_rss', 'showDonation');

// Load the header
add_action('wp_head', 'donation_wp_head');

// The welcome message
function donation_welcome() {
  if (get_option('donation_fresh') == 1) {
    echo '<div class="updated"><p><strong>'.__('Donation plugin has been activated successfully. To start using it, create a page and place into it the text {DONATION}','donation').'</strong></p></div>';
    update_option('donation_fresh','0');
  }
}

// Load the welcome message
add_action('admin_notices','donation_welcome');

// Load the welcome message
register_activation_hook(__FILE__,'donation_install');

// Install function
function donation_install() {
  // Call the installer
  check_donation_installed();
}

// Load the admin menu
add_action('admin_menu', 'donation_menu');

// Design the menu
function donation_menu() {
if (function_exists('add_menu_page'))
  {
    add_menu_page(__('Donation','donation'), __('Donation','donation'), 'manage_options', 'donation', 'donation_donors');
  }
if (function_exists('add_submenu_page'))
  {
    add_submenu_page('donation', __('Donors','donation'), __('Donors','donation'), 'manage_options', 'donation', 'donation_donors');
    add_submenu_page('donation', __('Options','donation'), __('Options','donation'), 'manage_options', 'donation-config', 'donation_config');
  }
}

// Config menu
function donation_config() {

  // Gather the submitted field
  if (isset($_POST['business'])) {
    update_option('donation_paypal_business',$_POST['business']);
    update_option('donation_paypal_lc',$_POST['lc']);
    update_option('donation_paypal_item_name',$_POST['item_name']);
    update_option('donation_paypal_currency_code',$_POST['currency_code']);
    update_option('donation_paypal_bn',$_POST['bn']);
    update_option('donation_currency_symbol',$_POST['currency_symbol']);
    update_option('donation_style',$_POST['style']);    
?>
<div class="updated">
   <p><?php _e('Donation configuration settings updated','donation'); ?></p>
</div>
<?php
  }

?>
<style type="text/css">
  <!--
  .error {
    background: lightcoral;
    border: 1px solid #e64f69 !important;
    margin: 1em 5% 10px !important;
    padding: 0 1em 0 1em !important;
  }
  .center {
    text-align: center;
  }
  .right {
    text-align: right;
  }
  .left {
    text-align: left;
  }
  .top {
    vertical-align: top;
  }
  .bold {
    font-weight: bold;
  }
  .private {
    color: #e64f69;
  }
  //-->
</style>
  <div class="wrap"><h2><?php _e('Donation Options','donation'); ?></h2>
<form name="quoteform" id="quoteform" class="wrap" method="post" action="<?php echo admin_url(); ?>admin.php?page=donation-config">
            <div id="linkadvanceddiv" class="postbox">
                        <div style="float: left; width: 98%; clear: both;" class="inside">
                                <table cellpadding="5" cellspacing="5">
                                <tr>
				  <td><legend><?php _e('PayPal e-mail address donations will be paid to','donation'); ?></legend></td>
				  <td><input style="width:200px;" type="text" name="business" value="<?php echo get_option('donation_paypal_business'); ?>" /></td>
                                </tr>
                                <tr>
				  <td><legend><?php _e('Locale of PayPal account','donation'); ?></legend></td>
                                  <td><input type="text" name="lc" value="<?php echo get_option('donation_paypal_lc'); ?>" /></td>
                                </tr>
                                <tr>
				  <td><legend><?php _e('Name of PayPal item that will appear on invoice','donation'); ?></legend></td>
                                  <td><input type="text" name="item_name" value="<?php echo get_option('donation_paypal_item_name'); ?>" /></td>
                                </tr>
                                <tr>
				  <td><legend><?php _e('Currency code PayPal will use for payments','donation'); ?></legend></td>
                                  <td><input type="text" name="currency_code" value="<?php echo get_option('donation_paypal_currency_code'); ?>" /></td>
                                </tr>
                                <tr>
				  <td><legend><?php _e('Symbol associated with the above currency code','donation'); ?></legend></td>
                                  <td><input type="text" name="currency_symbol" value="<?php echo get_option('donation_currency_symbol'); ?>" /></td>
                                </tr>
                                <tr>
				  <td><legend><?php _e('PayPal button coding - best leave this alone if unsure','donation'); ?></legend></td>
                                  <td><input style="width:350px;" type="text" name="bn" value="<?php echo get_option('donation_paypal_bn'); ?>" /></td>
                                </tr>
                                <tr>
			          <td style="vertical-align:top;"><legend><?php _e('CSS applied to plugin pages','donation'); ?></legend></td>
                                  <td><textarea name="style" style="width:400px; height:200px;"><?php echo get_option('donation_style'); ?></textarea></td>
                                </tr>
				</table>
                        </div>
			<div style="clear:both; height:1px;">&nbsp;</div>
                </div>
<input type="submit" name="submit" class="button bold" value="<?php _e('Save','donation'); ?> &raquo;" />
</form>
</div>
<?php
}

// Donor menu 
function donation_donors() {
  
  global $wpdb;

  if (isset($_GET['du'])) {
    if (isset($_GET['active'])) {
      if ($_GET['active'] == 0) {
        $wpdb->query("UPDATE ".WP_DONATION_TABLE." SET active = 0 WHERE id = ".$_GET['id']);
      }
      else if ($_GET['active'] == 1) {
        $wpdb->query("UPDATE ".WP_DONATION_TABLE." SET active = 1 WHERE id = ".$_GET['id']);
      }
    }
    if (isset($_GET['visible'])) {
      if ($_GET['visible'] == 0) {
	$wpdb->query("UPDATE ".WP_DONATION_TABLE." SET visible = 0 WHERE id = ".$_GET['id']);
      }
      else if ($_GET['visible'] == 1) {
	$wpdb->query("UPDATE ".WP_DONATION_TABLE." SET visible = 1 WHERE id = ".$_GET['id']);
      }
    }
?>
<div class="updated">
      <p><?php _e('Donor updated','donation'); ?></p>
</div>
<?php
  }
?>
<style type="text/css">
  <!--
  .error {
    background: lightcoral;
    border: 1px solid #e64f69 !important;
    margin: 1em 5% 10px !important;
    padding: 0 1em 0 1em !important;
  }
  .center {
    text-align: center;
  }
  .right {
    text-align: right;
  }
  .left {
    text-align: left;
  }
  .top {
    vertical-align: top;
  }
  .bold {
    font-weight: bold;
  }
  .private {
  color: #e64f69;
  }
  //-->
</style>
<div class="wrap">
    <h2><?php _e('Manage Donors','donation'); ?></h2>
    <table class="widefat page" width="100%" cellpadding="3" cellspacing="3">
      <thead>
        <tr>
	  <th class="manage-column" scope="col"><?php _e('Name','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Address','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Country','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Message','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('E-Mail','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Phone','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Amount','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Time','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Status','donation') ?></th>
	  <th class="manage-column" scope="col"><?php _e('Visibility','donation') ?></th>
        </tr>
      </thead>
      <tbody>
<?php
  $givers = $wpdb->get_results("SELECT * FROM ".WP_DONATION_TABLE."");
  if (!empty($givers))
    {
      foreach ($givers as $giver)
	{
	  ?><tr>
	    <td><?php echo stripslashes($giver->fname).' '.stripslashes($giver->lname); ?></td>
	    <td><?php echo stripslashes($giver->addr1).'<br />'.stripslashes($giver->town).', '.stripslashes($giver->county).'<br />'.stripslashes($giver->postcode); ?></td>
	    <td><?php echo stripslashes($giver->country); ?></td>
	    <td><?php echo '"'.substr(stripslashes($giver->message),0,14).'..."'; ?></td>
	    <td><?php echo '<a href="mailto:'.stripslashes($giver->email).'">'.stripslashes($giver->email).'</a>'; ?></td>
	    <td><?php echo stripslashes($giver->phone); ?></td>
	    <td><?php echo get_option('donation_currency_symbol').stripslashes($giver->amount); ?></td>
	    <td><?php echo date('jS F Y H:m',strtotime(stripslashes($giver->time))); ?></td>
            <td><?php
if ($giver->active == 1) {
  echo '<a href="'.admin_url().'admin.php?page=donation&du=1&active=0&id='.$giver->id.'" title="Click to mark unpaid">Paid</a>';
 }
else if ($giver->active == 0) {
  echo '<a href="'.admin_url().'admin.php?page=donation&du=1&active=1&id='.$giver->id.'" title="Click to mark paid">Unpaid</a>';
 }
?></td>
            <td><?php
if ($giver->visible == 1) {
  echo '<a href="'.admin_url().'admin.php?page=donation&du=1&visible=0&id='.$giver->id.'" title="Click to make invisible">Visible</a>';
 }
else if ($giver->visible == 0) {
  echo '<a href="'.admin_url().'admin.php?page=donation&du=1&visible=1&id='.$giver->id.'" title="Click to make visible">Invisible</a>';
 }
?></td>
          </tr><?php
	}
    }
?>
      </tbody>
    </table>
</div>
<?php
}

// PayPal amount check function
function check_paypal_amount($amount) {
    if (preg_match('/^[1-9]{1}[0-9]{1}\,{0,1}[0-9]{1,3}\.{1}[0-9]{2}$/',$amount) == 1) { return 1; } // Tens of thousands
    else if (preg_match('/^[1-9]{1}\,{0,1}[0-9]{1,3}\.{1}[0-9]{2}$/',$amount) == 1) { return 1; } // Thousands
    else if (preg_match('/^[1-9]{1}[0-9]{1,2}\.{1}[0-9]{2}$/',$amount) == 1) { return 1; } // Hundreds
    else if (preg_match('/^[1-9]{1}[0-9]{1}\.{1}[0-9]{2}$/',$amount) == 1) { return 1; } // Tens
    else if (preg_match('/^[1-9]{1}\.{1}[0-9]{2}$/',$amount) == 1) { return 1; } // Units
    else { return 0; }
}

// Check that the plugin is installed, if not, add the correct table
function check_donation_installed() {
  global $wpdb;
  if (get_option('donation_version') != '1.0.0') {
    // Install the donation table
    $tableSql = "CREATE TABLE IF NOT EXISTS " . WP_DONATION_TABLE . " (
`id` int(8) NOT NULL auto_increment,
`ok_seed` bigint UNSIGNED NOT NULL,
`fail_seed` bigint UNSIGNED NOT NULL,
`fname` varchar(255) character set utf8 NOT NULL,
`lname` varchar(255) character set utf8 NOT NULL,
`addr1` varchar(255) character set utf8 NOT NULL,
`addr2` varchar(255) character set utf8 NOT NULL,
`town` varchar(255) character set utf8 NOT NULL,
`county` varchar(255) character set utf8 NOT NULL,
`postcode` varchar(255) character set utf8 NOT NULL,
`country` varchar(255) character set utf8 NOT NULL,
`phone` varchar(255) character set utf8 NOT NULL,
`email` varchar(255) character set utf8 NOT NULL,
`amount` float NOT NULL,
`active` tinyint(1) NOT NULL default '0',
`visible` tinyint(1) NOT NULL default '0',
`message` text character set utf8 NOT NULL,
`time` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
    $wpdb->get_results($tableSql);

    // Set the default values of the various changable fields
    update_option('donation_fresh','1');
    update_option('donation_paypal_business','kieran@kieranoshea.com');
    update_option('donation_paypal_lc','GB');
    update_option('donation_paypal_item_name','Website Donation');
    update_option('donation_paypal_currency_code','GBP');
    update_option('donation_paypal_bn','PP-DonationsBF:btn_donateCC_LG.gif:NonHosted');
    update_option('donation_currency_symbol','&pound;');
    update_option('donation_style','.donation-table td {
  padding:2px !important;
  text-align:left !important;
}
.donation-table td input {
  width:150px;
  border:1px #000000 solid !important;
}
.donation-table td textarea {
  border:1px #000000 solid !important;
}
.donation-submission {
  padding:5px !important;
}
.donation-form {
  padding-bottom:50px !important;
}
.donation-image {
  float:right !important;
}
.donation-error {
  background-color:#F8E7E7;
  padding:10px !important;
  border:1px dotted #000000 !important;
  margin-bottom:5px;
  width:80%;
  font-size:120%;
}
.donation-verify {
  background-color:#C8E7E7;
  padding:10px !important;
  border:1px dotted #000000 !important;
  width:80%;
  font-size:120%;
}
.donation-summary form input {
  font-size:120%;
  padding:5px !important;
}
.donation-summary form {
  text-align:left !important;
}
.donation-test-box {
  background-color:#F8E7E7;
  padding:10px !important;
  border:1px dotted #000000 !important;
  margin-bottom:5px;
  min-height:50px;
  width:80%;
}
.donation-complete {
  background-color:#C8E7E7;
  padding:10px !important;
  border:1px dotted #000000 !important;
  margin-bottom:5px;
  width:80%;
}
.donor-block {
  padding:10px !important;
  border:1px dotted #000000 !important;
  margin-bottom:5px !important;
  min-height:50px;
  width:80%;
}');

    // Finally set the version to stop this block running agains
    update_option('donation_version','1.0.0');                                  
  }
}

// Place the CSS in the header
function donation_wp_head()
{
  echo '<style type="text/css">
';
  echo get_option('donation_style');
  echo '</style>
';
}

// The main bulk of the app
function donationApp () {
    global $wpdb;

    // Variables required in the application, in future to be taken from options 
    if (!isset($_GET['inprog']))
    {
        // Form unique seeds
        $ok_seed_ok = 1;
        while ($ok_seed_ok == 1)
        {
            $ok_seed = rand(10000000,99999999);
            $ok_seed_ok = $wpdb->get_var("SELECT count(id) FROM ".WP_DONATION_TABLE." WHERE ok_seed = '".$ok_seed."'");
        }
        $fail_seed_ok = 1;
        while ($fail_seed_ok == 1)
        {
            $fail_seed = rand(10000000,99999999);
            $fail_seed_ok = $wpdb->get_var("SELECT count(id) FROM ".WP_DONATION_TABLE." WHERE fail_seed = '".$fail_seed."'");
        }
        
        // Get the current donors data for display
        $donor_data = '';
        $givers = $wpdb->get_results("SELECT * FROM ".WP_DONATION_TABLE." WHERE active = 1 and visible = 1");
        if (!empty($givers))
        {
            $numcount = 1;
            foreach ($givers as $giver)
            {
                // Setup multi colour rows
                if ($numcount%2 == 1) { $col_bit = '#C8E7E7'; } else { $col_bit = '#F8E7E7'; }
                // Display a row with gravatar photo for each donor
		$gravatar = md5(strtolower(trim(stripslashes($giver->email))));
                $donor_data = $donor_data.'
                <div style="background-color:'.$col_bit.';" class="donor-block">
                <div style="float:left;margin-right:10px;">
<img alt="" src="http://www.gravatar.com/avatar/'.$gravatar.'?s=40&amp;d=mm" class="avatar avatar-40 photo" height="40" width="40" />
</div>
                <div><strong>'.stripslashes($giver->fname).' '.stripslashes($giver->lname).'</strong> '.__('on','donation').' '.date('jS F Y',strtotime($giver->time)).'
                <br /><br />"'.stripslashes($giver->message).'"</div>
                </div>';
                $numcount = $numcount+1;
            }
        }
        
        // Format the donors section
        $donors = '<div style="clear:both;"><h2>'.__('Donors','donation').'</h2>
<p>'.__('The following readers have generously given donations','donation').'</p><br />'.$donor_data.'</div>';

        // Echo the output the for tha main body of the donation, including form to fill
        $output = '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div>
<p>'.__('Your donation helps to pay for the infrastructure that keeps this site on the web and allows us to keep providing content you enjoy. Please give as generously as you can. Payments are collected securely via PayPal and the details you enter in this form are not shared with any other website.','donation').'<br /></p>
<div class="donation-form"><form action="'.get_permalink().'?inprog=1" method="post">
<input type="hidden" name="ok_seed" value="'.$ok_seed.'" />
<input type="hidden" name="fail_seed" value="'.$fail_seed.'" />
<div style="float:left;"><table class="donation-table donation-first">
<tr><td>'.__('First Name','donation').':</td><td> <input type="text" name="fname" value =""/></td></tr>
<tr><td>'.__('Last Name','donation').':</td><td> <input type="text" name="lname" value =""/></td></tr>
<tr><td>'.__('Address (1st Line)','donation').':</td><td> <input type="text" name="addr1" value =""/></td></tr>
<tr><td>'.__('Address (2nd Line)','donation').':</td><td> <input type="text" name="addr2" value =""/></td></tr>
<tr><td>'.__('Town / City','donation').':</td><td> <input type="text" name="town" value =""/></td></tr>
<tr><td>'.__('County','donation').':</td><td> <input type="text" name="county" value =""/></td></tr>
<tr><td>'.__('Post Code','donation').':</td><td> <input type="text" name="postcode" value =""/></td></tr>
<tr><td>'.__('Country','donation').':</td><td> <input type="text" name="country" value =""/></td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td>'.__('Phone Number','donation').':</td><td> <input type="text" name="phone" value =""/></td></tr>
<tr><td>'.__('E-Mail','donation').':</td><td> <input type="text" name="email" value =""/></td></tr>
</table></div>
<div><table class="donation-table donation-second">
<tr><td>'.__('Donation Amount','donation').' ('.get_option('donation_currency_symbol').'):</td><td> <input style="width:100px;" type="text" name="amount" value =""/></td></tr>
<tr><td style="vertical-align:top;">'.__('Donation Message','donation').':</td><td> <textarea name="message" rows="8" cols=27"></textarea></td></tr>
<tr><td>&nbsp;</td>
<td><br /><input type="submit" name="submit" value="'.__('Proceed','donation').' &raquo;" class="donation-submission"></td></tr>
</table>
</div></form></div>
'.$donors;

        return $output;
    }
    else
    {   
        // We've not completed the process yet, we need to validate input, allow user to check input, and submit to paypal
        if (!isset($_GET['gok']) && $_POST['ok_seed'])
        {
            // Validate our fields first
	    if (!($_POST['fname']) || !($_POST['lname']) || !($_POST['addr1']) || !($_POST['town']) || !($_POST['county']) || !($_POST['postcode']) || !($_POST['country']) 
            || !($_POST['phone']) || !($_POST['amount']) || !($_POST['message']) || check_paypal_amount($_POST['amount']) == 0)
            {
	      $the_errors = '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div>
            <div class="donation-error">
            '.__('You have not filled in the following required details','donation').'<br /><br />
            <ul>
            ';
	    if (!($_POST['fname'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('First Name','donation').'</li>'; }
	    if (!($_POST['lname'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Last Name','donation').'</li>'; }
	    if (!($_POST['addr1'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Address (1st Line)','donation').'</li>'; }
	    if (!($_POST['town'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Town / City','donation').'</li>'; }
	    if (!($_POST['county'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('County','donation').'</li>'; }
	    if (!($_POST['postcode'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Post Code','donation').'</li>'; }
	    if (!($_POST['country'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Country','donation').'</li>'; }
            if (!($_POST['phone'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Phone Number','donation').'</li>'; }
            if (!($_POST['amount']) || check_paypal_amount($_POST['amount']) == 0) { 
	      $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Donation Amount','donation').' ('.__('format is','donation').' &lt;'.__('pounds','donation').'&gt; &lt;'.__('decimal','donation').'&gt; &lt;'.__('pence','donation').'&gt;, '.__('e.g.','donation').' <strong>10.00</strong>)</li>'; }
            if (!($_POST['message'])) { $the_errors = $the_errors.'<li style="font-size:100%;">'.__('Donation Message','donation').'</li>'; }
            $the_errors = $the_errors.'</ul><br />
            <a href="javascript: history.go(-1)">'.__('Click here to go back and try again','donation').'</a> 
            </div>';
                return $the_errors;
            }
            else
            {
            // Store the DB entry, check to see if we're dealing with a correction
            $updating = $wpdb->get_var("SELECT count(id) FROM ".WP_DONATION_TABLE." WHERE ok_seed = '".mysql_real_escape_string($_POST['ok_seed'])."'");
            if ($updating = 1) 
            {
                $wpdb->query("DELETE FROM ".WP_DONATION_TABLE." WHERE ok_seed = '".mysql_real_escape_string($_POST['ok_seed'])."'");
            }
            $wpdb->query("INSERT INTO ".WP_DONATION_TABLE." (ok_seed,fail_seed,fname,lname,addr1,addr2,town,county,postcode,country,phone,email,amount,message) 
            VALUES ('".mysql_real_escape_string($_POST['ok_seed'])."','".mysql_real_escape_string($_POST['fail_seed'])."','".mysql_real_escape_string($_POST['fname'])."','".mysql_real_escape_string($_POST['lname'])."','".mysql_real_escape_string($_POST['addr1'])."','".mysql_real_escape_string($_POST['addr2'])."','".mysql_real_escape_string($_POST['town'])."','".mysql_real_escape_string($_POST['county'])."','".mysql_real_escape_string($_POST['postcode'])."','".mysql_real_escape_string($_POST['country'])."','".mysql_real_escape_string($_POST['phone'])."','".mysql_real_escape_string($_POST['email'])."','".mysql_real_escape_string($_POST['amount'])."','".mysql_real_escape_string($_POST['message'])."')");
	
	        // Prepare the user confirmation screen
            $ok_seed = stripslashes($_POST['ok_seed']);
            $fail_seed = stripslashes($_POST['fail_seed']);
            $amount = stripslashes($_POST['amount']);
            $paypal_pre_screen = '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div>
<p>'.__('The donation details you are submitting to us are as follows. Please confirm these are correct before continuing','donation').'.</p>';
            if ($_POST['addr2']) { $addr2 = '<br />'.stripslashes($_POST['addr2']); } else { $addr2 = ''; }
            $gravatar = md5(strtolower(trim(stripslashes($_POST['email']))));
            $paypal_detail_screen = '<div class="donation-verify"><table><tr>
            <td style="vertical-align:top;">
            <strong>'.stripslashes($_POST['fname']).' '.stripslashes($_POST['lname']).'</strong><br />
            '.stripslashes($_POST['addr1']).$addr2.'<br />
            '.stripslashes($_POST['town']).'<br />'.stripslashes($_POST['county']).'<br />
            '.stripslashes($_POST['postcode']).'<br />'.stripslashes($_POST['country']).'<br /><br />'.stripslashes($_POST['phone']).'<br />
            '.stripslashes($_POST['email']).'<br />
            </td>
            <td style="padding-left:40px;vertical-align:top;">
            <span style="font-size:170%;"><strong>'.get_option('donation_currency_symbol').stripslashes($_POST['amount']).'</strong></span><br /><br />
            <span style="font-size:120%;">"'.stripslashes($_POST['message']).'"</span><br />
            </td>
            </tr></table></div><br /><br />
<p>'.__('Your donation will appear on the website as follows','donation').'</p>
<div class="donation-test-box">
<div style="float:left;margin-right:10px;">
<img alt="" src="http://www.gravatar.com/avatar/'.$gravatar.'?s=40&amp;d=mm" class="avatar avatar-40 photo" height="40" width="40" />
</div>
<div><strong>'.stripslashes($_POST['fname']).' '.stripslashes($_POST['lname']).'</strong> '.__('on','donation').' '.date('jS F Y',time()).'
<br /><br />"'.stripslashes($_POST['message']).'"</div>
</div><br />
';
            
            // Prepare the paypal submit form
            $paypal_button_form = '<div class="donation-summary"><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="'.get_option('donation_paypal_business').'" />
<input type="hidden" name="lc" value="'.get_option('donation_paypal_lc').'" />
<input type="hidden" name="item_name" value="'.get_option('donation_paypal_item_name').'" />
<input type="hidden" name="amount" value="'.$amount.'" />
<input type="hidden" name="currency_code" value="'.get_option('donation_paypal_currency_code').'" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="rm" value="1" />
<input type="hidden" name="return" value="'.get_permalink().'?inprog=1&gok='.$ok_seed.'" />
<input type="hidden" name="cancel_return" value="'.get_permalink().'?inprog=1&gok='.$fail_seed.'" />
<input type="hidden" name="bn" value="'.get_option('donation_paypal_bn').'" />
<input type="button" name="back" value="&laquo; Amend donation details" onClick="history.go(-1)" />
<input type="submit" name="submit" value="Continue to payment &raquo;" />
</form></div>';
            return $paypal_pre_screen.$paypal_detail_screen.$paypal_button_form;
            }
        }
        else
        {
            // We've completed the process in some sense, so we check response and update database/user accordingly
            $ok = $wpdb->get_var("SELECT count(*) FROM ".WP_DONATION_TABLE." WHERE ok_seed = '".mysql_real_escape_string($_GET['gok'])."'");
            $ok_valid = $wpdb->get_var("SELECT active FROM ".WP_DONATION_TABLE." WHERE ok_seed = '".mysql_real_escape_string($_GET['gok'])."'");
            $fail = $wpdb->get_var("SELECT count(*) FROM ".WP_DONATION_TABLE." WHERE fail_seed = '".mysql_real_escape_string($_GET['gok'])."'");
            $fail_valid = $wpdb->get_var("SELECT active FROM ".WP_DONATION_TABLE." WHERE fail_seed = '".mysql_real_escape_string($_GET['gok'])."'");
            if ($ok == 1 && $ok_valid == 0)
            {
                $wpdb->query("UPDATE ".WP_DONATION_TABLE." SET active='1',visible='1' WHERE ok_seed = '".mysql_real_escape_string($_GET['gok'])."'");
                return '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div>
            <div class="donation-complete">
            '.__('Many thanks for your donation! Your name and message will now be displayed on the donation page','donation').'. <a href="'.get_permalink().'">'.__('Click here to go there now','donation').'</a>.
            </div>';
            }
            else if ($fail == 1 && $fail_valid == 0)
            {
                $wpdb->query("DELETE FROM ".WP_DONATION_TABLE." WHERE fail_seed = '".mysql_real_escape_string($_GET['gok'])."'");
                return '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div> 
            <div class="donation-error">
            '.__('You cancelled your payment so your donation was not sent','donation').'. <a href="'.get_permalink().'">'.__('Click here to try again','donation').'</a>. 
            </div>';
            }
            else
            {
	      return '<div class="donation-image"><img src="'. WP_PLUGIN_URL .'/'.basename(dirname(__FILE__)).'/donation_money.jpg" alt="'.__('money','donation').'" title="'.__('money','donation').'" /></div>
            <div class="donation-error">
            '.__('An error has occurred while processing your donation','donation').'. <a href="'.get_permalink().'">'.__('Click here to try again','donation').'</a>. 
            </div>';
            }
        }
    }
}

// Load the app into the page
function showDonation($content) {
    if (preg_match('/\{DONATION\}/',$content)) {
        $rendered = donationApp();
        $content = preg_replace('/\{DONATION\}/',$rendered,$content);
    }
    return $content;
}

?>
